package com.h3c.nem.service.impl;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.h3c.nem.client.AbilityClient;
import com.h3c.nem.dto.sap.SapXmlResponseDTO;
import com.h3c.nem.entity.SdDept;
import com.h3c.nem.entity.TbOfferWorker;
import com.h3c.nem.enums.IdTypeEnum;
import com.h3c.nem.enums.OfferWorkerStatusEnum;
import com.h3c.nem.sap.RfcManager;
import com.h3c.nem.service.ISapSyncService;
import com.h3c.nem.service.ISdDeptService;
import com.h3c.nem.service.ITbOfferWorkerService;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.EncryptionUtil;
import com.h3c.nem.utils.XmlConvertUtil;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoParameterList;
import com.sap.conn.jco.JCoStructure;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 同步sap员工
 *
 * @author chenyifan
 */
@Slf4j
@Service
@AllArgsConstructor
public class SapSyncServiceImpl implements ISapSyncService {

    private final RfcManager rfcManager;

    private final ITbOfferWorkerService workerService;

    private final ISdDeptService deptService;

    private final AbilityClient abilityClient;

    @Override
    @SneakyThrows
    public JCoStructure linkBpmGetData(String workerId) {
        //获取SAP客户端
        rfcManager.connect();
        JCoDestination destination = rfcManager.getDestination();
        //调用SAP接口
        JCoFunction function = rfcManager.getFunction(destination, "ZRFC_GET_OFFER");
        JCoParameterList importParameter = function.getImportParameterList();
        importParameter.setValue("PERNR", workerId);
        function.execute(destination);
        JCoParameterList exportParameterList = function.getExportParameterList();
        //获取输出表T_OUTPUT的数据
        return exportParameterList.getStructure("ZOFFER");
    }

    @Override
    @SneakyThrows
    public void getReserveStaff(String workerId) {
        TbOfferWorker existWorker = workerService.getById(workerId);
        if (Objects.nonNull(existWorker)) {
            throw new AppBusinessException("该员工已经同步");
        }
        JCoStructure returnStructure = linkBpmGetData(workerId);
        String certNo = returnStructure.getString("ICNUM");
        if (!StringUtils.hasText(certNo)) {
            throw new AppBusinessException("证件号不能为空");
        }
        TbOfferWorker offerWorker = new TbOfferWorker();
        if (StringUtils.hasText(certNo) && !StringUtils.containsWhitespace(certNo) && certNo.length() == 18) {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            try {
                offerWorker.setBirthday(sdf1.parse(certNo.substring(6, 10) + "-" + certNo.substring(10, 12) + "-" + certNo.substring(12, 14)));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        offerWorker
                .setWorkerId(workerId)
                .setWorkerName(returnStructure.getString("ENAME"))
                .setSex(returnStructure.getString("GESTX"))
                .setCertType(IdTypeEnum.ID_CARD)
                .setCertNo(certNo)
                .setPostName(abilityClient.getPostNameByPostId(returnStructure.getString("PLANS")))
                .setPostId(returnStructure.getString("PLANS"))
                .setDirectDeptId(returnStructure.getString("OBJID"))
                .setPhoneNo(returnStructure.getString("TELNR"))
                .setEmail(returnStructure.getString("USRID_LONG"))
                .setPersonnelRange(returnStructure.getString("NAME1"))
                .setPersonnelRangeCode(returnStructure.getString("WERKS"))
                .setHignTalentPostFlag(returnStructure.getString("ZGCGW"))
                .setInternationalTalentFlag(returnStructure.getString("ZGJHRC"))
                .setWorkCity(returnStructure.getString("ZTEXT1"))
                .setOuterCity(returnStructure.getString("ZTEXT2"))
                .setOfferProjectName(returnStructure.getString("ZZPMC"))
                .setSpecialApprovalFlag(returnStructure.getString("ZTPF"))
                .setSpecialApprovalType(returnStructure.getString("ZTPLX"))
                .setSpecialApprovalNote(returnStructure.getString("ZTPSM"))
                .setWorkerStatus(OfferWorkerStatusEnum.待发放offer)
                .setPreparationPassword(EncryptionUtil.encodeForBeiSenAndSap(certNo))
                .setDataSource("BPM")
                .setAlreadySave(false)
                .setUpdateTime(new Date())
                .setUpdatorInfo("sap同步")
                .setInType("社会招聘")
                .setNeedSignCompetition(returnStructure.getString("ZJYXYF"));
        SdDept sdDept = deptService.getById(returnStructure.getString("OBJID"));
        if(Objects.nonNull(sdDept)){
            String deptNameChain = sdDept.getDeptNameChain();
            if (StringUtils.hasText(deptNameChain)) {
                deptNameChain = deptNameChain.replaceAll("新华三/", "");
                List<String> splitTrim = StrUtil.splitTrim(deptNameChain, "/");
                for (int i = 0; i < splitTrim.size(); i++) {
                    ReflectUtil.setFieldValue(offerWorker,"dept"+(i+1)+"name",splitTrim.get(i));
                }
                offerWorker.setDeptNameChain(deptNameChain);
            }
        }
        workerService.save(offerWorker);
    }


    @Override
    public Boolean getIfThroughInvestigation(String workerId) throws Exception {
        String result = HttpRequest.post("http://bpm03.h3c.com:80/bpm/interface.nsf/h3c04010WS?OpenWebService")
                .header("ContentType", MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                .body("<soapenv:Envelope\n" +
                        "    xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'\n" +
                        "    xmlns:urn='urn:DefaultNamespace'>\n" +
                        "    <soapenv:Header/>\n" +
                        "    <soapenv:Body>\n" +
                        "        <urn:GETBDRESULT >\n" +
                        "            <EMPLOYEENO>" + workerId + "</EMPLOYEENO>\n" +
                        "        </urn:GETBDRESULT >\n" +
                        "    </soapenv:Body>\n" +
                        "</soapenv:Envelope>\n").execute().body();
        SapXmlResponseDTO responseDTO = XmlConvertUtil.convertToJavaBean(result, SapXmlResponseDTO.class);
        log.info("{}背调结果 {}", workerId, responseDTO);
        return JSONUtil.parseObj(responseDTO.getSoapenvBody().getGETBDRESULTResponse().getGETBDRESULTReturn()).getBool("success");
    }
}
